package com.bwton.msx.ccb.ui;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import com.bwton.msx.ccb.R;
import com.sensetime.ssidmobile.sdk.liveness.constants.STResultCode;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class ResultActivity extends Activity {

    public final static String EXTRA_DETECTION_RESULT = "EXTRA_DETECTION_RESULT";
    public final static String EXTRA_FROM_ACTIVITY = "EXTRA_FROM_ACTIVITY";
    public final static int INTERACTIVE = 1;
    public final static int SILENT = 2;
    public final static int COLOR = 3;

    public static void start(Context context, Result result) {
        Intent starter = new Intent(context, ResultActivity.class);
        starter.putExtra(EXTRA_DETECTION_RESULT, result);
        context.startActivity(starter);
    }

    protected TextView mTxtResult;
    protected RecyclerView mRecyclerView;
    protected ImageView mImageResult;
    protected ProgressBar mProgressBar;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_liveness_result);
        mTxtResult = findViewById(R.id.txt_result);
        mRecyclerView = findViewById(R.id.recycler);
        mImageResult = findViewById(R.id.result_bitmap);
        mProgressBar = findViewById(R.id.progress_circular);
        findViewById(R.id.goHome).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        findViewById(R.id.quit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        Result result = getIntent().getParcelableExtra(EXTRA_DETECTION_RESULT);
        int resultCode = result.resultCode;
        String resultMessage = result.resultMessage;
        if (resultCode == STResultCode.OK) {
            mTxtResult.setText("活体检测成功");
        } else if (resultCode == STResultCode.HACK) {
            mTxtResult.setText(R.string.txt_detect_fail);
            mTxtResult.setTextColor(Color.RED);
            mTxtResult.setCompoundDrawables(null, null, null, null);
        } else if (resultCode == STResultCode.TIME_OUT) {
            mTxtResult.setText(R.string.txt_error_timeout);
            mTxtResult.setTextColor(Color.RED);
            mTxtResult.setCompoundDrawables(null, null, null, null);
        } else if (resultCode == STResultCode.FACE_LOST) {
            mTxtResult.setText(R.string.txt_error_cancel_face_lost);
            mTxtResult.setTextColor(Color.RED);
            mTxtResult.setCompoundDrawables(null, null, null, null);
        } else if (resultCode == STResultCode.LOAD_LICENSE_FAILED) {
            mTxtResult.setText("加载license出错");
            mTxtResult.setTextColor(Color.RED);
            mTxtResult.setCompoundDrawables(null, null, null, null);
        } else if (resultCode == STResultCode.LICENSE_DISABLE) {
            mTxtResult.setText("不支持该业务");
            mTxtResult.setTextColor(Color.RED);
            mTxtResult.setCompoundDrawables(null, null, null, null);
        } else if (resultCode == STResultCode.DEFAKE_FAILED) {
            mTxtResult.setText("Defake失败");
            mTxtResult.setTextColor(Color.RED);
            mTxtResult.setCompoundDrawables(null, null, null, null);
        } else if (resultCode == STResultCode.DEFAKE_FRAMES_NOT_ENOUGH) {
            mTxtResult.setText("Defake帧不足");
            mTxtResult.setTextColor(Color.RED);
            mTxtResult.setCompoundDrawables(null, null, null, null);
        } else if (resultCode == STResultCode.DEFAKE_TIME_OUT) {
            mTxtResult.setText("Defake超时");
            mTxtResult.setTextColor(Color.RED);
            mTxtResult.setCompoundDrawables(null, null, null, null);
        } else {
            mTxtResult.setText(getString(R.string.txt_error_canceled) + resultCode);
            mTxtResult.setTextColor(Color.RED);
            mTxtResult.setCompoundDrawables(null, null, null, null);
        }

        LinkedList<String> paths = new LinkedList<>();
        if (result.bitmapFilePaths != null) {
            for (int i = 0, count = result.bitmapFilePaths.size(); i < count; i++) {
                paths.add(result.bitmapFilePaths.get(i));
            }
        }

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(RecyclerView.HORIZONTAL);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mRecyclerView.addItemDecoration(
                new DividerItemDecoration(this, DividerItemDecoration.HORIZONTAL));
        ResultAdapter resultAdapter = new ResultAdapter(paths);
        Log.i("截图", ": "+paths.toString());
        resultAdapter.addItemClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                if (view instanceof ImageView) {
                    mImageResult.setImageDrawable(((ImageView) view).getDrawable());
                }
            }
        });
        mRecyclerView.setAdapter(resultAdapter);
        //默认选中第一张
        mRecyclerView.getViewTreeObserver().
                addOnGlobalLayoutListener(
                        new ViewTreeObserver.OnGlobalLayoutListener() {
                            @Override
                            public void onGlobalLayout() {
                                try {
                                    ResultViewHolder resultViewHolder =
                                            (ResultViewHolder) (mRecyclerView.getChildViewHolder(
                                                    mRecyclerView.getChildAt(0)));
                                    resultViewHolder.mImageView.performClick();
                                } catch (Exception e) {
                                    // 识别失败
                                    e.printStackTrace();
                                }
                            }
                        });
    }

    public static class ResultAdapter extends RecyclerView.Adapter<ResultViewHolder> {

        List<String> mFilePath = new ArrayList<>();
        View.OnClickListener mItemClickListener;

        ResultAdapter(LinkedList<String> paths) {
            mFilePath.clear();
            mFilePath.addAll(paths);
        }

        @NonNull
        @Override
        public ResultViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            return new ResultViewHolder(LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_result_bitmap, null));
        }

        @Override
        public void onBindViewHolder(@NonNull ResultViewHolder holder, int position) {
            final String path = mFilePath.get(position);
            try {
                Bitmap bitmap = BitmapFactory.decodeFile(path);
                holder.mImageView.setImageBitmap(bitmap);
                holder.mImageView.setOnClickListener(mItemClickListener);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public int getItemCount() {
            return mFilePath.size();
        }

        public void addItemClickListener(View.OnClickListener onClickListener) {
            mItemClickListener = onClickListener;
        }
    }

    private static class ResultViewHolder extends RecyclerView.ViewHolder {
        ImageView mImageView;

        public ResultViewHolder(@NonNull View view) {
            super(view);
            mImageView = view.findViewById(R.id.bitmap);
        }
    }

    public static class Result implements Parcelable {
        public int resultCode;
        public String resultMessage;
        List<String> bitmapFilePaths = new ArrayList<>();

        @Override
        public int describeContents() {
            return 0;
        }

        @Override
        public void writeToParcel(Parcel dest, int flags) {
            dest.writeInt(this.resultCode);
            dest.writeString(this.resultMessage);
            dest.writeStringList(this.bitmapFilePaths);
        }

        public void readFromParcel(Parcel source) {
            this.resultCode = source.readInt();
            this.resultMessage = source.readString();
            this.bitmapFilePaths = source.createStringArrayList();
        }

        public Result() {
        }

        protected Result(Parcel in) {
            this.resultCode = in.readInt();
            this.resultMessage = in.readString();
            this.bitmapFilePaths = in.createStringArrayList();
        }

        public static final Creator<Result> CREATOR = new Creator<Result>() {
            @Override
            public Result createFromParcel(Parcel source) {
                return new Result(source);
            }

            @Override
            public Result[] newArray(int size) {
                return new Result[size];
            }
        };
    }
}
